<!-- 
  可选择的标签列表。目前只支持单选

  props：
    list [Array] 标签列表数据。其中对象影包含：name 展示的文本；key 唯一标识，为空时用 name 代替
    active [String|Number] 设置选中项，值为 list 项中的 key
    closeable [Boolean] 是否可删除。默认为 false。

  event
    onClick 点击后的回调方法。接受参数: 
        index 数组计数, 
    onClose 关闭后的回调方法。接受参数: 
        index 数组计数, 
 -->

<template>
  <div class="_tag-list">
    <div class="_tag-list-warp">
      <el-tag
        v-for="item in list"
        :key="getKey(item)"
        effect="plain"
        type="info"
        :class="{'active': isActive(item)}"
        @click="onClickTag(item)"
        :closeable="isActive(item) ? false : closeable"
        @close="onCloseTag(item)"
      >
        {{item.name}}
      </el-tag>
    </div>
  </div>
</template>

<script>
  import {
    Tag,
  } from 'element-ui'

  import {
    replaceEmpty
  } from '@utils/utils'

  export default {
    name: 'tag-list',
    components: {
      [Tag.name]: Tag,
    },
    props: {
      list: Array,
      active: null,
      closeable: false,
    },

    data() {
      return {
        activeTabType: this.getActiveTabType(),
      }
    },

    watch: {
      active() {
        this.activeTabType = this.getActiveTabType()
      },
    },

    methods: {
      getActiveTabType() {
        return replaceEmpty(this.active, this.getKey(this.list[0]))
      },

      getKey(item) {
        return item ? replaceEmpty(item.key, item.name) : ''
      },

      isActive(item) {
        return this.getKey(item) == this.activeTabType
      },
      onClickTag(item) {
        // TODO: 排除 onCloseTag 事件
        if (this.isActive(item))
          return
        const key = this.getKey(item)
        this.activeTabType = key
        this.$emit('onClick', key, item)
      },
      onCloseTag(item) {
        const key = this.getKey(item)
        this.$emit('onClose', key, item)
      }
    },

    created() {},
  }
</script>

<style lang="less" scoped>
  @import "~@style_pc/basic/utils/index";
  @height: @input-height;

  ._tag-list {
    position: relative;

    ._tag-list-warp {
      margin-bottom: 0 - @size-xs;
    }

    /deep/ .el-tag {
      position: relative;
      height: @height;
      line-height: @height;
      margin-bottom: @size-xs;
      transition: @base-transition;
      cursor: pointer;

      &:hover,
      &.active {
        background-color: @white;
        border-color: mix(@white, @color-main, 50%);
        color: @color-main;
        transition: @base-transition;
      }

      &+.el-tag {
        margin-left: @size-xs;
      }
    }
  }
</style>
